package com.company.cloud.uba.modules.app.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.redis.service.RedisUtils;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.uba.modules.app.controller.req.UserBrowseObjLogQuery4PageParam;
import com.company.cloud.uba.modules.app.mapper.UserBrowseObjMapper;
import com.company.cloud.uba.modules.app.models.RelDataResp;
import com.company.cloud.uba.modules.app.service.UbaRelDataService;
import com.company.cloud.uba.modules.base.entity.UserBrowseObjLog;
import com.company.cloud.uba.modules.base.service.UserBrowseObjLogService;
import com.company.cloud.uba.modules.cache.models.UserBrowseObjLogModel;
import com.company.cloud.uba.modules.cache.utils.UbaConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.function.Function;

/**
 * 访问日志服务
 */
@Login
@RestController
@RequestMapping("/app/uba/browseObjLog")
@Api(tags="Uba_访问日志服务")
public class UserBrowseObjLogAppController {

    @Autowired
    private UserBrowseObjLogService userBrowseObjLogService;
    @Autowired
    private UbaRelDataService ubaRelDataService;
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private UserBrowseObjMapper userBrowseObjMapper;


    @PostMapping("/queryBrowseObjLog")
    @ApiOperation(value="用户访问日志查询", response= UserBrowseObjLogModel.class)
    public BaseResult queryBrowseObjLog(@RequestBody UserBrowseObjLogQuery4PageParam params) {
        LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
        String shareCode=userInfo.getShareCode();

        System.out.println(JSON.toJSONString(userInfo));
        if(!StringUtils.isEmpty(userInfo.getToken())){
            LoginUserInfo  userInfo1 = redisUtils.get(userInfo.getToken(), LoginUserInfo.class);
            shareCode=userInfo1.getShareCode();
        }

        //todo:查询需要优化（建议用批先处理数据）
        IPage<UserBrowseObjLog> page = userBrowseObjLogService.page(
                new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<UserBrowseObjLog>()
                         .select("max(id) AS id",
                                 "company_no AS companyNo",
                                 "user_id AS userId",
                                 "third_user_id AS thirdUserId",
                                 "referral_user_id AS referralUserId",
                                 "rel_id_type AS relIdType",
                                 "rel_id AS relId" ,
                                 "max(cdt) AS cdt"
                         )
                        .eq("referral_code",shareCode)
                        .and(qw->qw.ne("user_id", userInfo.getId()).or().isNull("user_id"))
                        .eq(CheckUtils.hasInt(params.getUserId()),"user_id",params.getUserId())
                        .eq(StringUtils.hasText(params.getRelIdType()),"rel_id_type",params.getRelIdType())
                        .eq(StringUtils.hasText(params.getRelId()),"rel_id",params.getRelId())
                        .groupBy("company_no","user_id","third_user_id",
                                "referral_user_id", "rel_id_type","rel_id")
                        .orderByDesc("cdt")
        );

        if(CollectionUtils.isEmpty(page.getRecords())){
            return BaseResult.ok();
        }

        RelDataResp relDataResp= ubaRelDataService.getBrowseObjLogRelData(page.getRecords());

        IPage<UserBrowseObjLogModel> data = page.convert(new Function<UserBrowseObjLog, UserBrowseObjLogModel>() {
            @Override
            public UserBrowseObjLogModel apply(UserBrowseObjLog entity) {
                return  UbaConvertUtil.getUserBrowseObjLog(entity,relDataResp);
            }
        });

        return BaseResult.ok(data);
    }







}
